/**
 * Created by guobaogang on 2018/9/13.
 */
import React, {Component} from 'react';
import {Button, Loading, Panel} from 'tinper-bee';
import ReactDOM from 'react-dom';
import {base, createPage, getUrlParam, high, promptBox, toast} from 'nc-lightapp-front';
import {hrAjax as ajax, saveValidate} from 'src/hrpub/common/utils/utils';
import handdleCheckedData from '../../../public/functions/checkDataPermissionAction';
import './index.less';
import Header from "./components/Header";
import MainTable from "./components/MainTable";
import EditForm from "./components/EditForm";
import FileUpload from "./components/FileUpload";
import AddNew from "./components/AddNew"
import getOneAgreementInfo from "./container/functions/getOneAgreementInfo"
import updateButtonStatus from "./container/functions/updateButtonStatus";
import getMainTableData from "./container/functions/getMainTableData";
import getAgreementTypeData from "./container/functions/getAgreementType";
import deleteAgreementData from "./container/functions/deleteAgreementData";
import effectiveAgreementData from './container/functions/effectiveAgreementData'
import saveAgreementData from "./container/functions/saveAgreementData";
import EmptyImg from "src/hrpub/common/components/emptyImg";
import { handleHash } from 'src/hrpub/common/utils/utils';
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import WpsModal from 'src/hrpub/common/components/wpsPreModel';
const appcode = "60110503", pagecode = "60110503p", tableId = 'list', format = "YYYY-MM-DD";

// const reqData = [
// 	{
// 		rqUrl: '/platform/templet/querypage.do',
// 		rqJson: `{\n  \"pagecode\": \"60110501p\",\n  \"appcode\": \"60110501\"\n}`,
// 		rqCode: 'searchQuery'
//     },
//     {
// 		rqUrl: '/platform/templet/querypage.do',
// 		rqJson: `{\n  \"pagecode\": \"${pagecode}\",\n  \"appcode\": \"${appcode}\"\n}`,
// 		rqCode: 'template'
// 	},
// 	{
// 		rqUrl: '/platform/appregister/queryallbtns.do',
// 		rqJson: `{\n  \"pagecode\": \"${pagecode}\",\n  \"appcode\": \"${appcode}\"\n}`,
// 		rqCode: 'button'
// 	},
// 	{
// 		rqUrl: '/platform/appregister/queryappcontext.do',
// 		rqJson: `{\n  \"appcode\": \"${appcode}\"}`,
// 		rqCode: 'context'
// 	}
// ];

class ProChange extends Component {
    constructor(props) {
        super(props);
        this.registed=['agreementCard', 'postcontCardBefore', 'postcontCardAfter', 'secrerycontCardBefore', 'secrerycontCardAfter', 'traincontCardBefore', 'traincontCardAfter', 'traincontBaseCard', 'agreementCard_add', 'traincontCardBefore_add', 'traincontCardAfter_add', 
            'postcont', 'secrerycont', 'traincont', 'releasecontlist', 'psnList', 'chgPsnList']
        if (props.use) {
            props.use.form('agreementCard', 'postcontCardBefore', 'postcontCardAfter', 'secrerycontCardBefore', 'secrerycontCardAfter', 'traincontCardBefore', 'traincontCardAfter', 'traincontBaseCard', 'agreementCard_add', 'traincontCardBefore_add', 'traincontCardAfter_add')
            props.use.editTable('postcont', 'secrerycont', 'traincont', 'releasecontlist', 'psnList', 'chgPsnList')
            props.use.search('agreementQuery', 'listquery')
        }
        this.config = {
            pagecode: pagecode,
            appcode: appcode
        };
        this.state = {
            json: {},
            refreshFlag: false, // 是否点击刷新按钮
            loadingShow: false,
            orgVal: {}, // 存储组织
            dataList: [], // 存储所有协议类型，用于下拉选择框
            agreementType: null, // 协议类型 20190711 默认从协议类型接口中获取第一个数据
            isEdit: false, // 判断是不是编辑状态
            pageFlag: "list", // 判断页面展示 list:列表 card：卡片
            deletePks: [],// 删除数据主键','分割
            effectivePks: "", // 生效数据主键','分割
            editPk: '', // 卡片界面主键存储
            isRefer: false,
            index: '', // 协议类型多语
            pageInfo: { // 分页信息
                pageIndex: 1,
                pageSize: "10",
                total: "0",
                totalPage: "",
            },
            nodeRefs: {wpsview: null},
            origFormrelation: [] // 存一份原始的Formrelation
        };

        // snCreateUIDom({}, reqData, (data) => {
        //     let queryTemplate = data.searchQuery;
        //     let oid = queryTemplate.listquery && queryTemplate.listquery.oid;
        //     let postcont = data.template.postcont.items;
        //     let secrerycont = data.template.secrerycont.items;
        //     let traincont = data.template.traincont.items;
        //     this.setState({
        //         buttons: data.button || [],
        //         context: data.context || {},
        //         oid: oid
        //     });
        //     let callback = (json, status, inlt) => {
        //         if (status) {
        //             this.setState({//存json和inlt到页面state中并刷新页面
        //                 json
        //             }, () => {
        //                 this.initMeta(postcont, this);
        //                 this.initMeta(secrerycont, this);
        //                 this.initMeta(traincont, this);
        //                 this.setTemplateData(data);
        //             })
        //         }
        //     }
        //     props.MultiInit.getMultiLang({moduleId: 'cm6011', domainName: 'hrcm', callback});
        //     props.meta.setMeta(data && data.template ? data.template : {});
        //     props.meta.addMeta(queryTemplate);
        //     props.button.setButtons(data && data.button ? data.button : {});
        // });

        props.createUIDom(this.config, (data) => {
            let oid = data.template.listquery && data.template.listquery.oid;
            let postcont = data.template.postcont.items;
            let secrerycont = data.template.secrerycont.items;
            let traincont = data.template.traincont.items;
            this.setState({
                buttons: data.button || [],
                context: data.context || {},
                oid: oid,
                pageid: data.template.pageid
            });
            let callback = (json, status, inlt) => {
                if (status) {
                    console.log('..........这这')
                    this.setState({//存json和inlt到页面state中并刷新页面
                        json,
                        origFormrelation: data.template.formrelation
                    }, () => {
                        console.log(this.state.origFormrelation)
                        this.initMeta(postcont, this);
                        this.initMeta(secrerycont, this);
                        this.initMeta(traincont, this);
                        this.setTemplateData(data);
                        
                    })
                }
            }
            let temp = deepCopy(data.template);
            for (let key in temp) {
                if(temp.hasOwnProperty(key) && temp[key].moduletype){
                    if(!this.registed.includes(temp[key].code)) {
                        temp[key].moduletype === 'form' && props.use.form(temp[key].code);
                        temp[key].moduletype === 'table' && props.use.editTable(temp[key].code);
                        this.registed.push(temp[key].code);
                    }
            　　}
            }
            props.MultiInit.getMultiLang({moduleId: 'cm6011', domainName: 'hrcm', callback});
            props.meta.setMeta(data && data.template ? data.template : {});
            props.button.setButtons(data && data.button ? data.button : {});
        });
        this.updateOrgValue = this.updateOrgValue.bind(this);
        this.updateAgreeType = this.updateAgreeType.bind(this);
        this.updateState = this.updateState.bind(this);
        this.updateButtonStatus = this.updateButtonStatus.bind(this);
    }

    async componentWillMount() {
        await getAgreementTypeData.call(this);
        updateButtonStatus.call(this, this.state.orgVal, this.state.agreementType, this.state.isEdit);
        // console.log(this)
        
    }

    componentDidMount() {
        if (window.location.href.match('localhost:3006'))
            window.location.hash = '?page=201908171119';
        window.hh = this
    }

    /**
     * 获取一个或多个主键的字符串
     * @param deleteData
     * @returns {string} 主键之间用，分割
     */
    getAgreementPksString(deleteData) {
        let pk_agreements = [];
        let { agreementType, customAgreement } = this.state;
        if (this.state.pageFlag === 'card') { //卡片界面
            pk_agreements.push(this.state.editPk);
        } else if (this.state.pageFlag === 'list') { //列表界面
            let data = deleteData ? deleteData : this.props.editTable.getCheckedRows(customAgreement ? customAgreement : agreementType);
            if (data instanceof Array) {
                for (const index in data) {
                    pk_agreements.push(data[index].data.values.pk_agreement.value);
                }
            } else {
                pk_agreements.push(data.values.pk_agreement.value);
            }
        } else {
            return;
        }
        
        return pk_agreements;
    }

    //列表分页
    paginationEve(key) {
        this.state.pageInfo.pageIndex = key;
        // getMainTableData.call(this);
        let getConditions = this.props.search.getQueryInfo('listquery',true);
        let conditions = getConditions;
        getMainTableData.call(this,conditions);
    }

    //选择每页显示的条数
    pageSizeSelect(pageSize) {
        this.setState({
            pageInfo: {
                pageIndex: this.state.pageInfo.pageIndex,
                pageSize: pageSize,
            }
        }, () => {
            // getMainTableData.call(this);
            let getConditions = this.props.search.getQueryInfo('listquery',true);
            let conditions = getConditions;
            getMainTableData.call(this,conditions);
        })
    }

    //修改列表数据
    modifyListData(obj) {
        let pk_agreement = obj.values.pk_agreement.value;
        this.setState({
            editPk: pk_agreement
        }, () => {
            handdleCheckedData(pk_agreement, 'edit', 'agreement', ()=>{
                this.updateState({
                    btnCode: 'edit',
                    pageFlag: 'card',
                    isEdit: true,
                }, () => {
                    this.refs.editForm.setMainFormEdit('edit')
                })
            });
        })
    }

    // //删除列表数据
    // isDeleteRowData(obj) {
    //     let pk_agreement = obj.values.pk_agreement.value;
    //     handdleCheckedData(pk_agreement, 'delete', 'agreement', ()=>{
    //         this.deleteButtonClick(obj);
    //     });
    // }

    //协议文本
    contractText(obj) {
        this.textButtonClick(obj);
    }

    //设置模板信息
    setTemplateData(data){
        let listIdArr = new Set();
        let template = data && data.template;
        for( let name in template){
            if(name.indexOf('List') >= 0){
                listIdArr.add(name)
            }
        }
        listIdArr = Array.from(listIdArr);
        // console.log(listIdArr);
        listIdArr.forEach((v,i)=>{
            let dataItems = data.template[v].items;
            this.initMeta(dataItems,this);
        });
    }

    initMeta(data, opt) {
        let json = this.state.json;
         // 添加序号列
         data.unshift({
            attrcode: 'index',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['cm6011-000152'], // 国际化处理： 序号
            width: '65px',
            textAlign: 'center',
            visible: true,
            fixed: 'left',
            render(text, record, index) {
                return (
                    <span>{index + 1}</span>
                )
            }
        });

        data.forEach((item, key) => {  //添加协议编号超链接
            switch (item.attrcode) {
                case 'contcode':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.width = '120px'
                    item.render = (text, record, index) => {
                        return (
                            <span className="itemSpan" style={{color: '#0073E1', cursor: 'pointer'}}
                              onClick={this.onRowDoubleClick.bind(this, record, index)}>
                                {record && record.values['contcode'] && record.values['contcode'].value}
                        </span>
                        );
                    };
                    break;
                case 'pk_psndoc.code':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.width = '120px'
                    item.render = (text, record, index) => {
                        return (
                            <span className="itemSpan" onClick={this.onRowDoubleClick.bind(this, record, index)}>
                                {record && record.values['pk_psndoc.code'] && record.values['pk_psndoc.code'].value}
                            </span>
                        );
                    };
                    break;
                case 'pk_psndoc.name':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.width = '120px'
                    item.render = (text, record, index) => {
                        return (
                            <span className="itemSpan" onClick={this.onRowDoubleClick.bind(this, record, index)}>
                                {record && record.values['pk_psndoc.name'] && record.values['pk_psndoc.name'].value}
                            </span>
                        );
                    };
                    break;
                default: break;
            }
        });
        //添加附件
        data.push({
            attrcode: 'attachment',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['cm6011-000062'], /* 国际化处理： 附件管理*/
            width: '110px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                // let billId = record.values.pk_agreement.value;
                // let billNo = record.values.agreementcode.value
                return (
                    <span className="icon-file-icon-fujianshenpi">
                        <i className="icon iconfont icon-fujianshenpi" onClick={
                            opt.flieCheckedData.bind(opt, record)
                        }>&nbsp;</i>
                    </span>
                )
            }
        });
        data.push({
            attrcode: 'handleArea',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['cm6011-000064'], /* 国际化处理： 操作*/
            width: '250px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                return (
                    <div>
                        {/*修改*/}
                        <span style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                              onClick={opt.modifyListData.bind(opt, record)}
                        >
                            {json['cm6011-000067']}
                        </span>
                        {/*删除*/}
                        <span style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                              onClick={opt.deleteButtonClick.bind(opt, record)}
                        >
                            {json['cm6011-000065']}
                        </span>
                        {/*协议文本*/}
                        <span style={{color: '#0073E1', cursor: 'pointer'}}
                              onClick={opt.contractText.bind(opt, record)}
                        >
                            {json['cm6011-000113']}
                        </span>
                    </div>
                )
            }
        });
    }

    //更新组织
    updateOrgValue(value) {
        this.setState({
            orgVal: value
        }, () => {
            if (!value.refpk) {
                this.props.editTable.setTableData(this.agreementType, {rows: []}, false);
            } else {
                this.getMainTableData();
            }
            updateButtonStatus.call(this, this.state.orgVal, this.state.agreementType);
        })
    }

    //更新按钮状态
    updateButtonStatus() {
        updateButtonStatus.call(this, this.state.orgVal, this.state.agreementType);
    }

    //更新协议类型
    updateAgreeType(value) {
        let customAgreement; //如果是自定义模板则添加List
        let { orgVal, agreementType } = this.state;
        if(value && value.indexOf('hrcm_agreement') === 0){
            customAgreement = value + 'List';
            this.setState({
                customAgreement: customAgreement
            })
        }else{
            this.setState({
                customAgreement: customAgreement
            })
        }
        this.setState({
            agreementType: value
        }, () => {
            if (!value) {
                this.props.editTable.setTableData(value, {rows: []}, false);
                updateButtonStatus.call(this, orgVal, agreementType);
            } else if(!!orgVal.refpk) {
                this.getMainTableData();
            }
        })

    }

    /**
     * 更新table状态,并执行事件
     * @param obj ={
     *          btnCode: btnCode, //触发事件
     *          pageFlag: 'card', //显示页面
     *          isEdit: true, // 是否编辑状态
     *          }
     */
    updateState(obj,callback) {
        let{ agreementType, orgVal, editPk} = this.state;
        let cardId = "agreementCard";
        let paramObj = {
            agreementType: agreementType,
            baseForm: cardId,
            beforeForm: this.state.agreementType + "CardBefore",
            afterForm: this.state.agreementType + "CardAfter"
        };
        this.setState({
            paramObj
        });
        this.setDataBeforeFormKey(paramObj);
        if (obj.btnCode === "add") {
        } else if (obj.btnCode === "edit") {
            getOneAgreementInfo.call(this);
            this.props.editTable.setStatus(cardId, 'edit');
        }
        if (obj.btnCode === 'cancel' || obj.btnCode === "detail" || obj.btnCode === "save") {
            getOneAgreementInfo.call(this);
            this.props.editTable.setStatus(cardId, 'browse');
            // this.refs.header.setCardPaginationVisible(true, editPk)
        }
        this.setState({
            pageFlag: obj.pageFlag, //页面状态
            isEdit: obj.isEdit,
        }, () => {
            updateButtonStatus.call(this,orgVal, agreementType, obj.isEdit)
            if (this.state.pageFlag === 'list') {
                this.getMainTableData();
            }
        });
        callback && callback();
    }

    //保存按钮点击事件
    saveButtonClick() {
        let {json, pageid, formrelation} = this.state;
        let agreementType = this.state.agreementType;
        let cardId = "agreementCard";
        let ifprop = this.props.form.getFormItemsValue("agreementCard", 'ifprop').value === 'Y'; //是否试用
        let bodys_code = null;
        let billType = 'form';
        //校验日期
        if (agreementType === 'postcont' && ifprop) {
            let begindate1 = this.props.form.getFormItemsValue("agreementCard", 'probegindate').value; //试用开始日期
            let enddate1 = this.props.form.getFormItemsValue("agreementCard", 'probenddate').value; //试用结束日期
            let trmbegindate = this.props.form.getFormItemsValue("agreementCard", 'begindate').value; //协议开始日期
            let trmenddate = this.props.form.getFormItemsValue("agreementCard", 'enddate').value; // 协议结束日期
            if (trmbegindate && trmbegindate !== '') {
                let trmTimeNum = parseInt(new Date(trmbegindate).getTime());
                let proTimeNum = parseInt(new Date(begindate1).getTime());
                if (proTimeNum < trmTimeNum) {
                    toast({color: 'danger', content: json['cm6011-000132']}); /*【试用开始日期】不能小于【协议开始日期】！*/
                    return;
                }
            }
            if (trmenddate && trmenddate !== '') {
                let trmTimeNum = parseInt(new Date(trmenddate).getTime());
                let proTimeNum = parseInt(new Date(enddate1).getTime());
                if (proTimeNum > trmTimeNum) {
                    toast({color: 'danger', content: json['cm6011-000133']}); /*【试用结束日期】不能大于【协议结束日期】！*/
                    return;
                }
            }
        }
        if(formrelation.length > 0){
            bodys_code = formrelation;
            billType = 'extcard';
        }
        saveValidate(this.props, pageid, cardId, bodys_code, billType).then(()=>{
            if (this.props.form.isCheckNow(cardId)) {
                promptBox({
                    color: 'info',
                    title: json['cm6011-000071'], // 生效
                    content: json['cm6011-000048'], //是否立即生效？
                    beSureBtnName: json['cm6011-000057'], //是
                    cancelBtnName: json['cm6011-000058'], //否
                    hasCloseBtn: true,
                    noFooter: false,
                    noCancelBtn: false,
                    beSureBtnClick: () => {
                        this.setState({
                            isRefer: true
                        }, () => {
                            saveAgreementData.call(this)
                        })
                        this.refs.editForm.setMainFormEdit('browse')
                    },
                    cancelBtnClick: () => {
                        this.setState({
                            isRefer: false
                        }, () => {
                            saveAgreementData.call(this)
                        })
                        this.refs.editForm.setMainFormEdit('browse')
                    }
                });
            }
        })
    }

    //修改按钮点击事件
    editButtonClick(btnCode) {
        let json = this.state.json;
        const agreementType = this.state.agreementType;
        let pk_agreement = '';
        if (this.state.pageFlag === 'list') {
            const selectData = this.props.editTable.getClickRowIndex(agreementType);
            if (selectData && selectData.record) {
                pk_agreement = selectData.record.values.pk_agreement.value;
            }
        } else if (this.state.pageFlag === 'card') {
            pk_agreement = this.state.editPk;
        }
        if (!pk_agreement || pk_agreement === '') {
            toast({color: 'warning', content: json['cm6011-000106']}); /*请选择要操作的协议*/
            return;
        }

        handdleCheckedData(pk_agreement, 'edit', 'agreement', ()=>{
            this.updateState({
                btnCode: btnCode,
                pageFlag: 'card',
                isEdit: true,
                pk_agreement: pk_agreement,
            }, () => {
                this.refs.editForm.setMainFormEdit('edit')
            })
        });
    }


    //查询单据数据
    getMainTableData() {
        getMainTableData.call(this);
    }

    //表单双击事件
    onRowDoubleClick(record, index) {
        this.setState({
            editPk: record.values.pk_agreement.value,
            record
        }, () => {
            this.updateState({
                btnCode: 'detail', //触发事件
                pageFlag: 'card', //显示页面
                isEdit: false, // 是否编辑状态
                pk_agreement: record.values.pk_agreement.value //数据主键
            })
        })
    }

    // 新增按钮事件
    addButtonClick() {
        this.refs.addNew.setNewIncreasedDis(true)
    }

    //删除按钮事件(批量删除不传deleteData)
    deleteButtonClick(v) {
        let { agreementType, json, customAgreement } = this.state;
        let pks = [];
        if( !!v ){
            pks.push(v && v.values.pk_agreement.value);
        }else{
            pks = this.getAgreementPksString();
        }
        if (!!pks.length) {
            handdleCheckedData(pks, 'delete', 'agreement', ()=>{
                promptBox({
                    color: 'warning',
                    title: json['cm6011-000041'], /*确认删除*/
                    content: json['cm6011-000042'], /*您确定要删除选择数据吗？*/
                    beSureBtnName: json['cm6011-000057'], // 是
                    cancelBtnName: json['cm6011-000058'], // 否
                    hasCloseBtn: true, // 是否有关闭
                    beSureBtnClick: () => {
                        this.setState({
                            deletePks: pks,
                        }, () => {
                            deleteAgreementData.call(this)
                        })
                    },
                });
            });
        } else {
            toast({color: 'warning', content: json['cm6011-000125']}); //请选择要删除的数据
        }

    }

    // 点击生效事件
    isTakeEffectEvent(){
        let { json } = this.state;
        let pks = this.getAgreementPksString();
        if (!!pks.length) {
            handdleCheckedData(pks, 'effect', 'agreement', ()=>{
                this.effectiveButtonClick(pks);
            });
        }else{
            toast({color: 'warning', content: json['cm6011-000135']})
        }
        
    }

    //生效按钮事件
    effectiveButtonClick(effectivePks) {
        let json = this.state.json;
        let { agreementType, customAgreement } = this.state;
        promptBox({
            color: 'warning',
            title: json['cm6011-000121'],
            content: json['cm6011-000134'],
            beSureBtnName: json['cm6011-000057'], // 是
            cancelBtnName: json['cm6011-000058'], // 否
            hasCloseBtn: true, // 是否有关闭
            noFooter: false, // 没有按钮
            noCancelBtn: false, //没有取消按钮
            beSureBtnClick: () => {
                this.setState({
                    effectivePks: effectivePks,
                }, () => {
                    effectiveAgreementData.call(this)
                })
            }
        });
       
    }

    //取消按钮事件
    cancelButtonClick(btnCode) {
        let json = this.state.json;
        promptBox({
            color: 'warning',
            title: json['cm6011-000000'], //确认取消
            content: json['cm6011-000123'], //是否确认取消
            beSureBtnName: json['cm6011-000057'], // 是
            cancelBtnName: json['cm6011-000058'], // 否
            hasCloseBtn: true, // 是否有关闭
            beSureBtnClick: () => {
                // let {form} = this.props;
                // form.EmptyAllFormValue('agreementCard');
                this.updateState({
                    btnCode: btnCode,
                    pageFlag: 'card',
                    isEdit: false
                }, () => {
                    this.refs.editForm.setMainFormEdit('browse')
                });
            }
        });
    }

    //刷新按钮事件
    refreshButtonClick() {
        this.state.refreshFlag = true;
        if (this.state.pageFlag === 'list') {
            this.getMainTableData.call(this);
        } else if (this.state.pageFlag === 'card') {
            getOneAgreementInfo.call(this);
        } else {
            return;
        }
        this.state.refreshFlag = false;
    }

    //添加附件校验事件
    flieCheckedData(rowRecord){
        let pk_agreement = '';
        if (this.state.pageFlag === 'list') {
            pk_agreement = rowRecord.values.pk_agreement.value;
        } else {
            pk_agreement = this.state.record.values.pk_agreement.value;
        }
        handdleCheckedData(pk_agreement, 'attachment', 'agreement', ()=>{
            this.fileButtonClick(pk_agreement);
        });
    }

    //列表附件管理
    // flieViewShow(rowRecord) {
    //     this.fileButtonClick(rowRecord);
    // }

    //附件管理按钮事件
    fileButtonClick(pk_agreement) {
        // let pk_psndoc_sub = '';
        // if (this.state.pageFlag === 'list') {
        //     pk_psndoc_sub = rowRecord.values.pk_psndoc.value;
        // } else {

        //     pk_psndoc_sub = this.state.record.values.pk_psndoc.value;
        // }
        this.refs.FileUpload.showUploader(pk_agreement);
    }

    // 协议文本操作
    textButtonClick(obj) {
        let json = this.state.json;
        let pk_agreement = '';
        let that = this;
        if (this.state.pageFlag === 'list') {
            if (obj && obj.values && obj.values.pk_agreement) {
                pk_agreement = obj.values.pk_agreement.value;
            } else {
                toast({color: 'warning', content: json['cm6011-000009']});// 请先选择数据！
                return;
            }
        } else {
            pk_agreement = this.state.editPk;
        }
        let paramObj = {
            pk_org: this.state.orgVal.refpk,
            pk_agreement: pk_agreement
        }
        ajax({
            url: '/nccloud/hrcm/templet/AgreementTextViewAction.do',
            data: paramObj,
            success: (result) => {
                if (result.success) {
                    if (this.state.pageFlag === 'list') {
                        this.state.nodeRefs.wpsview.openView([{data: obj}], 'ag')
                    } else {
                        let formData = this.props.form.getAllFormValue('agreementCard').rows;
                        this.state.nodeRefs.wpsview.openView(formData, 'ag')
                    }
                    // let origin = 'uclient://start/' + window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '')
                    // window.location.href = origin + result.data
                }
            }
        })
    }

    //打开查询
    listQuery () {
        let { orgVal } = this.state;
        this.props.search.openAdvSearch('listquery', true, ()=>{
            let meta = this.props.meta.getMeta();
            let items = meta.listquery.items;
            items.length > 0 && items.map((item,index)=>{
                if(item.attrcode === 'pk_psnjob.pk_dept'){
                    item.queryCondition = {
                        pk_hrorg: orgVal.refpk
                    }
                }
            })
            this.props.meta.setMeta(meta);
        });
    }
    // 查询数据
    searchData = () => {
        // let conditions = props.search.getAllSearchData('query').conditions || [];
        let getConditions = this.props.search.getQueryInfo('listquery',true);
        let conditions = getConditions;
        getMainTableData.call(this,conditions);
    }

    /**
     * 按钮点击事件
     * @param btnCode 按钮类型
     */
    onBtnClickOperation(btnCode) {
        switch (btnCode) {
            case 'add':
                this.addButtonClick()
                break;
            case 'edit':
                this.editButtonClick(btnCode)
                break;
            case 'delete':
                this.deleteButtonClick()
                break;
            case 'save':
                this.saveButtonClick()
                break;
            case 'effect':
                this.isTakeEffectEvent()
                break;
            case 'file':
                this.flieCheckedData()
                break;
            case 'text':
                this.textButtonClick()
                break;
            case 'cancel':
                this.cancelButtonClick(btnCode)
                break;
            case 'refresh':
                this.refreshButtonClick()
                break;
            case 'query': 
                this.listQuery();
                break;
            default:
                break;
        }
    }

    // 设置主表单编辑态
    setMainFormEdit() {
        this.refs.editForm.setMainFormEdit()
    }

    //设置主表单id
    setMainFormId(){
        this.refs.editForm.setCardId();
    }

    // 调用editForm的setDataBeforeFormKey方法
    setDataBeforeFormKey(paramObj) {
        this.refs.editForm.setDataBeforeFormKey(this.props, paramObj)
    }

    //操作卡片翻页
    handleCardPagination(pk) {
        this.setState({
            editPk: pk
        }, () => {
            getOneAgreementInfo.call(this)
        })
    }

    //设置卡片界面基本表显示数据
    setCardColumnShow(){
        let { agreementType } = this.state;
        let cardId = "agreementCard";
        let baseMeta = this.props.meta.getMeta()[cardId];
        // 培训协议会多展现几个字段
        if (agreementType === 'traincont') {
            baseMeta.items.map(obj => {
                switch (obj.attrcode) {
                    case 'pk_psnjob.pk_org':
                        obj.visible = true;
                        break;
                    case 'pk_psnjob.pk_dept':
                        obj.visible = true;
                        break;
                    case 'pk_psnjob.pk_post':
                        obj.visible = true;
                        break;
                    case 'pk_psndoc.id':
                        obj.visible = true;
                        break;
                    case 'pk_psnjob.pk_job':
                        obj.visible = true;
                        break;
                    default:
                        break;
                }
            })
        } else {
            baseMeta.items.map(obj => {
                switch (obj.attrcode) {
                    case 'pk_psnjob.pk_org':
                        obj.visible = false;
                        break;
                    case 'pk_psnjob.pk_dept':
                        obj.visible = false;
                        break;
                    case 'pk_psnjob.pk_post':
                        obj.visible = false;
                        break;
                    case 'pk_psndoc.id':
                        obj.visible = false;
                        break;
                    case 'pk_psnjob.pk_job':
                        obj.visible = false;
                        break;
                    default:
                        break;
                }
            })
        }
    }
    render() {
        const { search } = this.props;
        const { NCCreateSearch } = search;
        const {orgVal, agreementType, isEdit, dataList, pageFlag, pageInfo, json,isCardFinish, isVisiblePagination, oid, cardId, pageid, nodeRefs} = this.state;
        if (document.getElementById('app')) {
            document.getElementById('app').style.height = pageFlag === "card" ? 'auto': '100%'
        }
        return (
            <div className="ProChange-list nc-single-table nc-bill-card">
                <Header {...this.props}
                        json={this.state.json}
                        ref="header"
                        orgVal={orgVal}
                        agreementType={agreementType}
                        dataList={dataList}
                        isEdit={isEdit}
                        pageFlag={pageFlag}
                        onBtnClickOperation={this.onBtnClickOperation.bind(this)}
                        handleCardPagination={this.handleCardPagination.bind(this)}
                        updateState={this.updateState}
                        updateAgreeType={this.updateAgreeType}
                        cancelButtonClick={this.cancelButtonClick.bind(this)}
                        setMainFormId ={this.setMainFormId.bind(this)}
                        updateOrgValue={this.updateOrgValue}/>
                    <div className="list-card">
                        {!orgVal.refpk || !agreementType ?
                            <EmptyImg text={json['cm6011-000096']}/>
                            :
                            <React.Fragment>
                                <div className="nc-single-table nc-bill-table-area" style={{display: pageFlag === "list" ? 'block' : 'none'}}>
                                    <MainTable
                                        {...this.props}
                                        json={this.state.json}
                                        orgVal={orgVal}
                                        agreementType={agreementType}
                                        pageInfo={pageInfo}
                                        isVisiblePagination={isVisiblePagination}
                                        onRowDoubleClick={this.onRowDoubleClick.bind(this)}
                                        paginationEve={this.paginationEve.bind(this)}
                                        pageSizeSelect={this.pageSizeSelect.bind(this)}
                                    />
                                </div>
                                <div className="change-card-from" style={{display: pageFlag === "card" ? true : 'none'}}>
                                    <div>
                                        <EditForm
                                            ref="editForm"
                                            {...this.props}
                                            json={this.state.json}
                                            orgVal={orgVal}
                                            cardId = {cardId}
                                            isCardFinish = {isCardFinish}
                                            agreementType={agreementType}
                                        />
                                    </div>
                                </div>
                            </React.Fragment>
                        }
                    </div>
                    <div style={{display: "none"}}>
                        {
                            NCCreateSearch('listquery', {
                                clickSearchBtn: ()=>{ this.searchData() },
                                onlyShowAdvArea: false,
                                showAdvSearchPlanBtn: true,
                                saveSearchPlan: true,
                                oid: oid,
                                onlyShowSuperBtn: true
                            })
                        }
                    </div>
                <div>
                    <FileUpload json={json} ref='FileUpload'/>
                </div>
                <div>
                    <AddNew
                        ref="addNew"
                        pkOrg={orgVal.refpk}
                        {...this.props}
                        json={json}
                        pageid = {pageid}
                        agreementType={agreementType}
                        registed = {this.registed}
                        setDataBeforeFormKey={this.setDataBeforeFormKey.bind(this)}
                        getMainTableData={this.getMainTableData.bind(this)}
                        setCardColumnShow = {this.setCardColumnShow.bind(this)}
                        setMainFormEdit={this.setMainFormEdit.bind(this)}/>
                </div>
                <WpsModal
                    {...this.props}
                    onRef ={ref => nodeRefs.wpsview = ref}
                    appcode={appcode}
                    pk_org={orgVal}
                   />
            </div>

        );
    }
}


const PeriodModel =  handleHash('201908171119', `c=${appcode}&p=${pagecode}`)(createPage({
    // billinfo: [{
    //     billtype: 'extcard', 
    //     pagecode: appcode, 
    //     headcode: 'agreementCard',
    //     bodycode: [
    //         "postcontCardBefore",
    //         "postcontCardAfter",
    //         "secrerycontCardBefore",
    //         "secrerycontCardAfter",
    //         "traincontCardBefore",
    //         "traincontCardAfter",
    //         "hrcm_agreement1CardAfter",
    //         "hrcm_agreement1CardBefore",
    //         "hrcm_agreement2CardAfter", 
    //         "hrcm_agreement2CardBefore"
    //     ]
    // }]
})(ProChange));
ReactDOM.render(<PeriodModel/>, document.querySelector('#app'));
export default ProChange;
